package com.example.shellshopping.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.shellshopping.login.UserBean;

public class SaveUserUtils {
    private  static UserBean.DataBean dataBean;

    //将用户信息保存到内存当中
    public static boolean saveUserToMemory(UserBean.DataBean bean){
        dataBean = bean;
        return true;
    }
    //将用户登录的个人信息保存到文件
    public static boolean saveUserToFile(Context context, UserBean.DataBean data){
        //共享参数保存数据的步骤
        //1、获取共享参数对象
        SharedPreferences pref = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        //2、获取编辑对象
        SharedPreferences.Editor editor = pref.edit();
        //3、开始写入数据
        editor.putInt("id",data.getId());
        editor.putString("phone",data.getPhone());
        editor.putString("password",data.getPassword());
        editor.putString("name",data.getName());
        editor.putString("address",data.getAddress());
        editor.putString("nickname",data.getNickname());
        editor.putString("question",data.getQuestion());
        editor.putString("answer",data.getAnswer());
        //4、提交结果
        editor.commit();
        //保存到内存中
        saveUserToMemory(data);
        return true;
    }

    //获取用户信息数据
    public static UserBean.DataBean getUserFromFile(Context context){
        //1、获取共享参数数据
        SharedPreferences pref = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        int id = pref.getInt("id",-1);
        String phone = pref.getString("phone","");
        String password = pref.getString("password","");
        String name = pref.getString("name","");
        String address = pref.getString("address","");
        String nickname = pref.getString("nickname","");
        String question = pref.getString("question","");
        String answer = pref.getString("answer","");
        UserBean.DataBean bean = new UserBean.DataBean();
        bean.setId(id);
        bean.setPhone(phone);
        bean.setName(name);
        bean.setPassword(password);
        bean.setAnswer(answer);
        bean.setQuestion(question);
        bean.setNickname(nickname);
        bean.setAddress(address);
        return bean;
    }

    //获取用户信息；先从内存开始获取，如果内存没有，从文件获取
    public  static UserBean.DataBean getUserInfo(Context context){
        if (dataBean!=null) {
            return dataBean;
        }
        UserBean.DataBean user = getUserFromFile(context);
        if (user.getId()!=-1) {
            dataBean = user;
            return dataBean;
        }
        return  null;
    }
    //  删除文件中和内存中的用户信息
    public static void deleteUserInfo(Context context){
        SharedPreferences pref = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.clear();    //清空文件中所有的数据
        editor.commit();
        dataBean = null;
    }
}
